package com.yuyu.qingmangmall.ware.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yuyu.common.constant.WareConstant;
import com.yuyu.common.utils.PageUtils;
import com.yuyu.common.utils.Query;
import com.yuyu.qingmangmall.ware.dao.PurchaseDao;
import com.yuyu.qingmangmall.ware.entity.PurchaseDetailEntity;
import com.yuyu.qingmangmall.ware.entity.PurchaseEntity;
import com.yuyu.qingmangmall.ware.service.PurchaseDetailService;
import com.yuyu.qingmangmall.ware.service.PurchaseService;
import com.yuyu.qingmangmall.ware.service.WareSkuService;
import com.yuyu.qingmangmall.ware.vo.MergeVo;
import com.yuyu.qingmangmall.ware.vo.PurchaseDoneVo;
import com.yuyu.qingmangmall.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    PurchaseDetailService purchaseDetailService;

    @Autowired
    WareSkuService wareSkuService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPageUnreceiveList(Map<String, Object> params) {

        QueryWrapper<PurchaseEntity> wrapper = new QueryWrapper<PurchaseEntity>();
        //  status 状态[0新建，1已分配，2正在采购，3已完成，4采购失败]
        wrapper.eq("status",0)
                .or().eq("status",1);
        IPage<PurchaseEntity> page = this.page(new Query<PurchaseEntity>().getPage(params),
                wrapper);

        return new PageUtils(page);
    }

    /**
     * 合并采购需求
     * @param mergeVo
     */
    @Transactional
    @Override
    public void purchaseMerge(MergeVo mergeVo) {
        Long purchaseId = mergeVo.getPurchaseId();
        if (purchaseId==null){
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            this.save(purchaseEntity);

            purchaseId = purchaseEntity.getId();
        }


        List<Long> items = mergeVo.getItems();
        Long finalPurchaseId = purchaseId;

        // 确认采购单状态是0，1才可以合并  采购需求状态是 0
        PurchaseEntity purchaseEntity1 = this.baseMapper.selectById(finalPurchaseId);
        if (purchaseEntity1.getStatus()==WareConstant.PurchaseStatusEnum.CREATED.getCode()
            || purchaseEntity1.getStatus()==WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()){

            List<PurchaseDetailEntity> collect = items.stream().filter(purc->{
                // 过滤出采购需求状态是 0的
                PurchaseDetailEntity byId = purchaseDetailService.getById(purc);
                return byId.getStatus()==WareConstant.PurchaseDetailStatusEnum.CREATED.getCode();

            }).map(item -> {
                PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
                detailEntity.setId(item);
                detailEntity.setPurchaseId(finalPurchaseId);
//                detailEntity.setStatus(WareConstant.PurchaseDetailStatusEnum.CREATED.getCode());
                return detailEntity;
            }).collect(Collectors.toList());


            if (collect.size()!=0){
                purchaseDetailService.updateBatchByIdAndStatusIsAssigned(collect);


                PurchaseEntity purchaseEntity = new PurchaseEntity();
                purchaseEntity.setId(finalPurchaseId);
                purchaseEntity.setUpdateTime(new Date());
                this.updateById(purchaseEntity); // 更新时间

            }


        }



    }

    /**
     * 领取采购单
     * @param ids 采购单Id们
     */
    @Transactional
    @Override
    public void purchaseReceived(List<Long> ids) {
        // 领取 采购单状态为新建或已分配的 采购单

        List<PurchaseEntity> purchaseEntities = this.listByIds(ids);
        List<PurchaseEntity> collect = purchaseEntities.stream().filter(purchase -> {
            // 过滤出采购单状态为新建或已分配的采购单
            return purchase.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode()
                    || purchase.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode();
        }).map(purc->{
            // 改变采购单的状态为已领取
            purc.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            // 改变修改时间
            purc.setUpdateTime(new Date());
            return purc;
        }).collect(Collectors.toList());

        this.updateBatchById(collect);

        // 拿到相应的采购需求
        List<PurchaseDetailEntity> details = purchaseDetailService.selectPurchaseDetailByPurchaseIds(ids);
        details.forEach(deta->{
            // 改变相应采购需求的状态为正在采购
            deta.setStatus(WareConstant.PurchaseDetailStatusEnum.PURCHASING.getCode());
        });
        purchaseDetailService.updateBatchById(details);


    }

    /**
     * 完成采购
     * @param purchaseDoneVo
     */
    @Transactional
    @Override
    public void purchaseDone(PurchaseDoneVo purchaseDoneVo) {


        // 改变采购需求状态
        List<PurchaseItemDoneVo> items = purchaseDoneVo.getItems();
        Boolean flag = true;

        List<PurchaseDetailEntity> detailEntityList = new ArrayList<>();
        for (PurchaseItemDoneVo item : items) {
            PurchaseDetailEntity detailEntity = new PurchaseDetailEntity();
            detailEntity.setId(item.getItemId());

            if (item.getStatus() == WareConstant.PurchaseDetailStatusEnum.HASERROR.getCode()) {
                detailEntity.setStatus(item.getStatus());

                flag = false;
//                break;
            } else {
                // 将成功采购的商品加入库存
                detailEntity.setStatus(item.getStatus());
                PurchaseDetailEntity detailEntity1 = purchaseDetailService.getById(item.getItemId());

                wareSkuService.addStock(detailEntity1.getSkuId(),detailEntity1.getSkuNum(),detailEntity1.getWareId());
            }

            detailEntityList.add(detailEntity);
        }
            purchaseDetailService.updateBatchById(detailEntityList);

        // 改变采购单状态
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        purchaseEntity.setId(purchaseDoneVo.getId());
//        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERROR.getCode());
//        this.baseMapper.updateById(purchaseEntity);

        if (flag){
            // 全部采购成功
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.FINISH.getCode());
            this.baseMapper.updateById(purchaseEntity);
        }else {
            // 采购失败
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.HASERROR.getCode());
            this.baseMapper.updateById(purchaseEntity);
        }

    }

}